/*
 * Copyright &copy; 2011-2020 lnint Inc. All right reserved.
 * 
 * 修改信息：【与SVN提交信息一致】
 * A: 新增类 王磊 2015-03-20 08:42:32
 */
package com.lnint.jess.generator.service;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.lnint.jess.common.persistence.Page;
import com.lnint.jess.common.service.BaseService;
import com.lnint.jess.common.utils.StringUtils;
import com.lnint.jess.generator.dao.GenSceneColumnDao;
import com.lnint.jess.generator.dao.GenSceneDao;
import com.lnint.jess.generator.dao.GenSceneRelateColumnDao;
import com.lnint.jess.generator.entity.GenScene;
import com.lnint.jess.generator.entity.GenSceneColumn;
import com.lnint.jess.generator.entity.GenSceneRelateColumn;
import com.lnint.jess.generator.utils.GenUtils;

/**
 * <P>代码生成场景管理Service</P>
 *
 * @version 2015-03-20
 * @author 王磊 2015-03-20 08:42:32
 * @since JDK 1.6
 */
@Service
@Transactional(readOnly = true)//配置事务.查询使用
public class GenSceneService extends BaseService {

	@Autowired
	private GenSceneDao genSceneDao;//注入dao层
	
	@Autowired
	private GenSceneColumnDao genSceneColumnDao;//注入dao层
	
	@Autowired
	private GenSceneRelateColumnDao genSceneRelateColumnDao;//注入dao层
	
	/**
	 * <P>获得实体模型数据</P>
	 * @param id 实体主键;
	 * @return GenScene
	 */
	public GenScene get(String id) {
		return genSceneDao.get(id);
	}
	/**
	 * <P>获得分页数据</P>
	 * @param page 分页实体;
	 * @param genScene 业务实体
	 * @return page 分页实体
	 */
	public Page<GenScene> find(Page<GenScene> page, GenScene genScene) {
	    //HQL查询条件
		DetachedCriteria dc = genSceneDao.createDetachedCriteria();
		if (StringUtils.isNotEmpty(genScene.getName())){
			dc.add(Restrictions.like("name", "%"+genScene.getName()+"%"));
		}
		dc.add(Restrictions.eq(GenScene.FIELD_DEL_FLAG, GenScene.DEL_FLAG_NORMAL));
		dc.addOrder(Order.desc("id"));
		//查询处理
		return genSceneDao.find(page, dc);
	}
	
	/**
	 * <P>查询所有场景数据</P>
	 * edit by weisu 15.3.24
	 */
	public List<GenScene> findAll() {
	    //HQL查询条件
		DetachedCriteria dc = genSceneDao.createDetachedCriteria();
		dc.add(Restrictions.eq(GenScene.FIELD_DEL_FLAG, GenScene.DEL_FLAG_NORMAL));
		dc.addOrder(Order.desc("id"));
		//查询处理
		return genSceneDao.find(dc);
	}
	
	/**
	 * <P>保存实体模型数据</P>
	 * @param reportMonthDetail 业务实体
	 * @return void
	 */	
	@Transactional(readOnly = false)
	public void save(GenScene genScene) {
		//clear()清除级联缓存，防止保存关联表报错，使用时请打开
		//genSceneDao.clear();
		//保存场景
		genSceneDao.save(genScene);
		//保存列信息配置
		List<GenSceneColumn> columnList = genScene.getColumnList();
		for (GenSceneColumn column : columnList){
			column.setGenSceneId(genScene);
			column.setJavaType(GenUtils.getJtype(column.getJdbcType()));
//			column.setJavaField(StringUtils.toCamelCase(column.getName()));
			if(!"1".equals(column.getIsEntity())){
				column.setIsEntity("0");
			}
			if(!"1".equals(column.getIsForm())){
				column.setIsForm("0");
			}
			if(!"1".equals(column.getIsList())){
				column.setIsList("0");
			}
			if(!"1".equals(column.getIsEdit())){
				column.setIsEdit("0");
			}
			if(!"1".equals(column.getIsQuery())){
				column.setIsQuery("0");
			}
			if(!"1".equals(column.getIsNull())){
				column.setIsNull("0");
			}
			if(!"1".equals(column.getQueryType())){
				column.setQueryType("0");
			}
			column.setIsSubtable("0");
			genSceneColumnDao.save(column);
		}
		//保存主表级联关系
		List<GenSceneRelateColumn> relcolumnList = genScene.getRelatecolumnList();
		for (GenSceneRelateColumn relcolumn : relcolumnList){
			GenSceneRelateColumn relcolumnNew= new  GenSceneRelateColumn();
			if(relcolumn.getRelateType() != null){
				if("99".equals(relcolumn.getInverseJoincolumn())) {
					genSceneRelateColumnDao.deleteById(relcolumn.getId());
				} else {
					relcolumnNew.setGenScene(genScene);
					relcolumnNew.setIsSubtable("0");
					relcolumnNew.setRelateEntity(relcolumn.getRelateEntity());
					relcolumnNew.setRelateType(relcolumn.getRelateType());
					relcolumnNew.setMappedby(relcolumn.getMappedby());
					relcolumnNew.setInverseJoincolumn(relcolumn.getInverseJoincolumn());
					relcolumnNew.setJavaField(relcolumn.getJavaField());
					relcolumnNew.setJoincolumn(relcolumn.getJoincolumn());
					relcolumnNew.setJointable(relcolumn.getJointable());
					relcolumnNew.setRelateOp(relcolumn.getRelateOp());
					relcolumnNew.setSettings(relcolumn.getSettings());
					relcolumnNew.setSort(relcolumn.getSort());
					genSceneRelateColumnDao.save(relcolumnNew);
				}
			}
		}
		
		//主从表场景，保存从表配置信息。
		if(genScene.getSceneType().equals("2")){
			List<GenSceneColumn> subcolumnList = genScene.getSubColumnList();
			for (GenSceneColumn subcolumn : subcolumnList){
				subcolumn.setGenSceneId(genScene);
				subcolumn.setJavaType(GenUtils.getJtype(subcolumn.getJdbcType()));
//				subcolumn.setJavaField(StringUtils.toCamelCase(subcolumn.getName()));
				if(!"1".equals(subcolumn.getIsEntity())){
					subcolumn.setIsEntity("0");
				}
				if(!"1".equals(subcolumn.getIsForm())){
					subcolumn.setIsForm("0");
				}
				if(!"1".equals(subcolumn.getIsList())){
					subcolumn.setIsList("0");
				}
				if(!"1".equals(subcolumn.getIsEdit())){
					subcolumn.setIsEdit("0");
				}
				if(!"1".equals(subcolumn.getIsQuery())){
					subcolumn.setIsQuery("0");
				}
				if(!"1".equals(subcolumn.getIsNull())){
					subcolumn.setIsNull("0");
				}
				if(!"1".equals(subcolumn.getQueryType())){
					subcolumn.setQueryType("0");
				}
				subcolumn.setIsSubtable("1");
				genSceneColumnDao.save(subcolumn);
			}
			
			//保存从表级联关系
			List<GenSceneRelateColumn> subrelcolumnList = genScene.getSubRelatecolumnList();
			for (GenSceneRelateColumn subrelcolumn : subrelcolumnList){
				GenSceneRelateColumn subrelcolumnNew= new  GenSceneRelateColumn();
				if(subrelcolumn.getRelateType() != null){
					if("99".equals(subrelcolumn.getInverseJoincolumn())) {
						genSceneRelateColumnDao.deleteById(subrelcolumn.getId());
					} else {
						subrelcolumnNew.setGenScene(genScene);
						subrelcolumnNew.setIsSubtable("1");
						subrelcolumnNew.setRelateEntity(subrelcolumn.getRelateEntity());
						subrelcolumnNew.setRelateType(subrelcolumn.getRelateType());
						subrelcolumnNew.setMappedby(subrelcolumn.getMappedby());
						subrelcolumnNew.setInverseJoincolumn(subrelcolumn.getInverseJoincolumn());
						subrelcolumnNew.setJavaField(subrelcolumn.getJavaField());
						subrelcolumnNew.setJoincolumn(subrelcolumn.getJoincolumn());
						subrelcolumnNew.setJointable(subrelcolumn.getJointable());
						subrelcolumnNew.setRelateOp(subrelcolumn.getRelateOp());
						subrelcolumnNew.setSettings(subrelcolumn.getSettings());
						subrelcolumnNew.setSort(subrelcolumn.getSort());
						genSceneRelateColumnDao.save(subrelcolumnNew);
					}
				}
			}
		}
	}
	
	/**
	 * <P>删除实体模型数据</P>
	 * @param id 实体模型主键
	 * @return void
	 */	
	@Transactional(readOnly = false)
	public void delete(String id) {
		genSceneDao.deleteById(id);
	}
	
	/**
	 * <P>根据表名获得表的基本信息</P>
	 * @param tablename 表名;
	 * @return GenScene
	 */
	public GenScene findTableList(String tablename) {
		return genSceneDao.get(tablename);
	}
	/**
	 * <P>根据表名获得表的 物理字段属性信息</P>
	 * @param tablename 表名;
	 * @return GenScene
	 */
	public List<GenSceneColumn> findTableColumnList(String tablename) {
		List<GenSceneColumn> columnList = Lists.newArrayList();	
		//dao查询
		List<Object>  retlist= genSceneDao.findTableColumnList(tablename);
		//遍历列属性LIST
        for(int i=0;i<retlist.size();i++){  
        	Object[] obj =(Object[])retlist.get(i);
        	//判断列是否为id，remarks createBy createDate updateBy updateDate delFlag
        	if(isDataEntityCol(obj[0].toString())==false){
                GenSceneColumn col=new GenSceneColumn();
                col.setName(obj[0].toString());//name
                col.setIsEntity("1");
                col.setIsNull(obj[1]==null?"":obj[1].toString());
                col.setSort(Integer.parseInt(obj[2]==null?"":obj[2].toString()));
                col.setComments(obj[3]==null?"":obj[3].toString());
                col.setJdbcType(obj[4]==null?"":obj[4].toString());
                col.setJavaField(StringUtils.toCamelCase(obj[0]==null?"":obj[0].toString()));
                //add one
                columnList.add(col);
        	}
         }
        return columnList;
	}
	/**
	 * <P>判断是否为DataEntity中的列</P>
	 * @param tablename 表名;
	 * @return GenScene
	 */
	public boolean isDataEntityCol(String colname) {
		boolean ret=false;
		if(colname.equalsIgnoreCase("id")){
			ret=true;
		}
		if(colname.equalsIgnoreCase("remarks")){
			ret=true;
		}
		if(colname.equalsIgnoreCase("CREATE_BY")){
			ret=true;
		}
		if(colname.equalsIgnoreCase("CREATE_DATE")){
			ret=true;
		}
		if(colname.equalsIgnoreCase("UPDATE_BY")){
			ret=true;
		}
		if(colname.equalsIgnoreCase("UPDATE_DATE")){
			ret=true;
		}
		if(colname.equalsIgnoreCase("DEL_FLAG")){
			ret=true;
		}		
		return ret;
		
	}
	/**
	 * <P>根据表名获得表的 表主键</P>
	 * @param tablename 表名;
	 * @return GenScene
	 */
	public String findTablePK(String tablename) {
		String pk="";
		//MYSQL 获得主键
//		StringBuffer querySql= new StringBuffer(" SELECT lower(au.COLUMN_NAME) AS columnName"
//				+ " FROM information_schema.`COLUMNS`"
//				+ " au WHERE au.TABLE_SCHEMA = (select database()) "
//				+ " AND au.COLUMN_KEY='PRI' AND au.TABLE_NAME = upper(:tabName)");
//		HashMap<String,Object> parameters =new HashMap<String,Object> ();
//		parameters.put("tabName", tablename);
//		List<Object> retlist = genSceneDao.findBySql(querySql.toString(),new Parameter(parameters));
//		//
//		if(retlist.size()>0){
//			pk=retlist.get(0).toString();
//		}
		return pk;
	}
	//
}
